package cn.myjerry.iter;

import java.util.Arrays;
import java.util.Iterator;

/**
 * 目标：深入迭代器的原理
 * 
 * @author Jerry
 *
 */

public class SxtDeepList {
	private String[] element = {"a","b","c","d","e"};
	private int size = element.length;	
	private int cursor = -1;
	
	public int size(){
		return size;
	}
	
	public void add(String str) {
		if(size > element.length - 1) {
			element = Arrays.copyOf(element, element.length+10);
		}
		element[size++] = str;
	}
	
	private class MyIter implements Iterator<String>{
		@Override
		public boolean hasNext() {
			return cursor+1 < size;
		}
		@Override
		public String next() {
			return element[++cursor];
		}
		@Override
		public void remove() {
			System.arraycopy(element, cursor, element, cursor+1, size-(cursor+1));
			size--;
			cursor--;
		}
	}
	
	public Iterator<String> iterator() {
		return new MyIter();
	}
	
	public static void main(String[] args) {
		SxtDeepList list = new SxtDeepList();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		list.add("ddd");
		Iterator<String> iter = list.iterator();
		while(iter.hasNext()) {
			iter.remove();
		}
		System.out.println(list.size());
	}
}
